<?php
namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Region extends Backend
{

    /**
     * Seniors模型对象
     * @var \app\admin\model\Seniors
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        // 父级ID
        $pid = $ids ? $ids : 0;
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where                                       = [];
            $where['pid']                                = $pid;
            $list                                        = db('region')->where($where)->where(['deletetime' => null])->order('weigh desc,id desc')->limit($offset, $limit)->select();
            $total                                       = db('region')->where($where)->where(['deletetime' => null])->count();
            $result                                      = ["total" => $total, "rows" => $list];

            return json($result);
        }

        $this->assignconfig("ids", $pid);
        $this->assignconfig("region_add_son", $this->auth->check("region/add_son"));
        $this->assignconfig("region_see_son", $this->auth->check("region/see_son"));
        $this->assignconfig("region_edit", $this->auth->check("region/edit"));
        $this->assignconfig("region_del", $this->auth->check("region/del"));
        return $this->view->fetch();
    }

    public function add($ids = null)
    {
        // 父级ID
        $pid         = $ids;
        $parent_name = db('region')->where(['id' => $pid])->value('name');
        $this->view->assign("pid", $pid);
        $this->view->assign("parent_name", $parent_name);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (! $params['name']) {
                    $this->error('请填写地区名称');
                }
                $params['level'] = 1;
                if ($params['pid']) {
                    $level = db('region')->where(['id' => $params['pid'], 'deletetime' => null])->value('level');
                    if (! $level) {
                        $this->error('上级地区有误,请刷新页面');
                    }
                    $params['level'] = $level + 1;
                }
                $params['createtime'] = time();
                $result               = false;
                Db::startTrans();
                try {
                    $result = db('region')->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        // 父级ID
        $row = db('region')->where(['id' => $ids])->find();
        if (! $row) {
            $this->error(__('No Results were found'));
        }

        $pid         = $row['pid'];
        $parent      = db('region')->where(['id' => $pid, 'deletetime' => null])->find();
        $parent_name = $parent['name'];
        $parent_list = db('region')->where(['pid' => $parent['pid'], 'deletetime' => null])->select();
        // dd($parent_list);
        $this->view->assign("parent_list", $parent_list);
        $this->view->assign("pid", $pid);
        $this->view->assign("parent_name", $parent_name);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (! $params['name']) {
                    $this->error('请填写地区名称');
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = db('region')->where(['id' => $row['id']])->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $list  = db('region')->where('id', 'in', $ids)->select();
            $count = 0;
            $time  = time();
            Db::startTrans();
            try {
                foreach ($list as $key => $value) {
                    $son = db('region')->where(['pid' => $value['id'], 'deletetime' => null])->count();
                    if ($son) {
                        Db::rollback();
                        $this->error('请先清空下级地区');
                    }
                    $region_id = $value['id'];
                }
                foreach ($list as $k => $v) {
                    $count += db('region')->where(['id' => $v['id']])->update(['deletetime' => $time]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /*
    *选择城市，城市联动
     */
    public function select($value = '')
    {
        $type     = $this->request->get('type');
        $group_id = $this->request->get('group_id');
        $list     = null;
        if ($group_id !== '') {
            if ($type == 'province') {
                $list = db('region')->field('id as value, name')->where(['level' => 1, 'pid' => 0, 'deletetime' => null])->select();
            } else {
                $list = db('region')->field('id as value, name')->where(['pid' => $group_id, 'deletetime' => null])->select();
            }
        }
        $this->success('', null, $list);
    }

    /*
    *选择城市，城市联动
     */
    public function area($value = '')
    {
        $row = $this->request->get('row/a');

       
        $province = isset($row['province'])?$row['province']:'';
        $city = isset($row['ciry'])?$row['city']:'';


        $where = [];

        $where['pid'] = 0;
        if ($province) {
            $where['pid'] = $province;
        }
        if ($city) {
            $where['pid'] = $city;
        }
        $where['deletetime'] = null;
        $list                = db('region')->field('id as value, name')->where($where)->select();
        $this->success('', null, $list);
    }

    /**
     * [searchlist 生成小程序地址]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-25T14:34:50+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function searchlist($value = '')
    {
        $set_list = [];
        $f        = db('region')->field('id,name')->where(['level' => 1, 'deletetime' => null])->order('weigh desc,id desc')->select();
        foreach ($f as $key => &$value) {
            $buf     = db('region')->field('id,name')->where(['pid' => $value['id'], 'deletetime' => null])->order('weigh desc,id desc')->select();
            $two_son = [];
            foreach ($buf as $k => &$v) {
                $bufs      = db('region')->where(['pid' => $v['id'], 'deletetime' => null])->order('weigh desc,id desc')->select();
                $three_son = [];
                $three_arr = [];
                foreach ($bufs as $kf => $vf) {
                    $three_son[] = '{ id: "' . $vf['id'] . '", name: "' . $vf['name'] . '",son:{}}';
                    $three_arr[] = ['id' => $vf['id'], 'name' => $vf['name']];
                }
                // $three_son =  implode(",", $three_son);
                // $two_son[] = '{ id: "'.$v['id'].'", name: "'.$v['name'].'",son:['.$three_son.'] }';
                $v['son'] = $three_arr;

            }
            $value['son'] = $buf;
            unset($v);

            // $two_son =  implode(",", $two_son);
            // $set_list[] = '{ id: "'.$value['id'].'", name: "'.$value['name'].'",son:['.$two_son.'] }';
        }
        unset($value);
        // 1
        // $set_list =  implode(",", $set_list);
        // $set_list = 'var brandjsdata = ['.$set_list.']';
        // $path = ROOT_PATH."public/assets/js/region.js";
        // file_put_contents($path,$set_list);

        $path = ROOT_PATH . "public/assets/js/region.json";
        file_put_contents($path, json_encode($f, JSON_UNESCAPED_UNICODE));
        $this->success('操作成功');
    }

}
